<template>
  <div class="app-container">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="postForm"
      label-position="right"
      label-width="100px"
      style="width: 400px; margin-left:50px;"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="postForm.roleName" clearable placeholder="角色名称" maxlength="20" />
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="postForm.roleCode" placeholder="角色编码" maxlength="20" />
      </el-form-item>
      <el-form-item label="角色类型" prop="roleType">
        <el-radio v-model="postForm.roleType" label="0" border >管理员角色</el-radio>
        <el-radio v-model="postForm.roleType" label="1" border >普通角色</el-radio>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input
          v-model="postForm.roleDesc"
          :autosize="{ minRows: 2, maxRows: 4}"
          type="textarea"
          placeholder="角色描述"
          maxlength="200"
        />
      </el-form-item>
      <el-form-item label="权限">
        <el-tree
          ref="tree"
          :data="resourceData"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          class="permission-tree"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-waves @click="$router.back()">返回</el-button>
        <el-button v-waves type="primary" @click="submitForm">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getRole, saveRole, updateRole, checkRoleCode } from '@/api/system/role'
import { resourceTree } from '@/api/system/resource'
import waves from '@/directive/waves' // waves directive

const defaultForm = {
  id: null,
  roleName: null,
  roleCode: null,
  roleDesc: null,
  roleType: 1,
  resourceIds: []
}

// 处理返回的资源数据生成资源选择树
export function filterResourceTree(resources) {
  const res = []
  resources.forEach(resource => {
    const tmp = {}
    tmp.id = resource.id
    tmp.label = resource.resourceName
    if (resource.children) {
      tmp.children = filterResourceTree(resource.children)
    }
    res.push(tmp)
  })
  return res
}
export default {
  name: 'RoleDetail',
  directives: { waves },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validRoleCode = (rule, value, callback) => {
      if (value === null || value.trim() === '') {
        callback(new Error('角色编码不能为空'))
      } else {
        if (this.oldRoleCode !== value) {
          this.checkRoleCode(value, callback)
        } else {
          callback()
        }
      }
    }

    return {
      postForm: Object.assign({}, defaultForm),
      resourceData: [],
      systemOptions: [],
      oldRoleCode: null,
      resourceIds: null,
      authSystemId: null,
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 15 个字符', trigger: 'change' }
        ],
        roleCode: [
          { min: 1, max: 20, message: '长度在 1 到 30 个字符', trigger: 'change' },
          { required: true, validator: validRoleCode, trigger: 'change' }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      // const authSystemId = this.$route.query.authSystemId
      // this.authSystemId = authSystemId
      this.loading = false
      this.getResourceTree()
    }
  },
  methods: {
    showResource() {
      this.getResourceTree()
    },
    fetchData(id) {
      getRole({ id: id }).then(response => {
        this.postForm = response.data
        this.oldRoleCode = response.data.roleCode
        this.authSystemId = response.data.authSystemId
        this.resourceIds = response.data.resourceIds
        this.getResourceTree()
      }).catch(err => {
        console.log(err)
      })
    },
    async getResourceTree() {
      resourceTree({ authSystemId: this.authSystemId }).then(response => {
        this.resourceData = filterResourceTree(response.data)
        if (this.resourceIds !== null) {
          this.$refs.tree.setCheckedKeys(this.resourceIds.split('@'))
        }
      })
    },
    checkRoleCode(roleCode, callback) {
      checkRoleCode({ roleCode: roleCode }).then(response => {
        const returnCode = response && response.returnCode
        if (returnCode !== this.Const.OK) {
          callback(new Error(response.msg))
        } else {
          callback()
        }
      })
    },
    submitForm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.postForm.resourceIds = this.$refs.tree.getCheckedKeys().join('@').concat('@').concat(this.$refs.tree.getHalfCheckedKeys().join('@'))
          if (this.isEdit) {
            updateRole(this.postForm).then(response => {
              const returnCode = response && response.returnCode
              if (this.Const.OK === returnCode) {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.$router.back()
              } else {
                this.$message({
                  type: 'error',
                  message: response && response.msg || '更新失败'
                })
              }
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '更新失败'
              })
            })
          } else {
            this.postForm.authSystemId = this.authSystemId
            saveRole(this.postForm).then(response => {
              const returnCode = response && response.returnCode
              if (this.Const.OK === returnCode) {
                this.$message({
                  type: 'success',
                  message: '保存成功'
                })
                this.$router.back()
              } else {
                this.$message({
                  type: 'error',
                  message: response && response.msg || '保存失败'
                })
              }
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '保存失败'
              })
            })
          }
        }
      })
    }
  }
}

</script>
<style scoped>

</style>
